package com.javafactroy.kunlong.bip.icp.message.base.codec;

import com.javafactroy.kunlong.bip.icp.message.base.consts.BodyTypeEnum;
import com.javafactroy.kunlong.bip.icp.message.data.app.LengthFieldStrMsg;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

@Component
public class LengthFieldBytes2StrDecoder {

    public static  void decode(LengthFieldStrMsg appMsg, ByteBuffer buf) {
        //LengthFieldBasedAppMsg appMsg = new LengthFieldBasedAppMsg();
        appMsg.setBodyTypeEnum(BodyTypeEnum.text);
        buf.rewind();
        appMsg.setLength(buf.getInt());
        byte[] bytes = new byte[buf.capacity() - 4];
        buf.get(bytes);
        appMsg.setBody(decodeBody(bytes));

    }

    public static LengthFieldStrMsg decode(ByteBuffer buf) {
        LengthFieldStrMsg appMsg = new LengthFieldStrMsg();
         decode(appMsg,buf);
        return appMsg;
    }
    public static int decodeLen(byte[] bytes) {
        ByteBuffer byteBuffer = ByteBuffer.wrap( bytes);
        return byteBuffer.getInt();

    }

    public static String decodeBody(byte[] bytes) {
        try {
            return new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
